package daily.may0516;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

//定义实现类(有点麻烦，不推荐)
class MyCompareRule implements Comparator<String>{
    @Override
    public int compare(String s1, String s2) {
        if (s1.length() >= s2.length()){
            return 1;//返回1为升序，返回-1为降序
        }
        return -1;
    }
}

public class SortComparatorTest {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        Collections.addAll(list,"Amy","Bob","Cloud","DaMing","Eve","Franklin","Gina");

        //使用实现类对象作为参数传入sort方法（有点麻烦，不推荐）,按字符串长度升序排序
        Collections.sort(list,new MyCompareRule());
        System.out.println(list);//[Amy, Bob, Eve, Gina, Cloud, DaMing, Franklin]

        //使用匿名内部类创建一个比较器，按字符串长度降序排序
        Collections.sort(list, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                if (s1.length() >= s2.length()){
                    return -1;//返回1为升序，返回-1为降序
                }
                return 1;
            }
        });
        System.out.println(list);//[Franklin, DaMing, Cloud, Gina, Eve, Bob, Amy]
    }
}
